package org.kust.bbs.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.kust.bbs.admin.mapper.AdminRoleMapper;
import org.kust.bbs.admin.mapper.RoleMapper;
import org.kust.bbs.admin.service.IRoleService;
import org.kust.bbs.common.ex.ServiceException;
import org.kust.bbs.common.web.JsonPage;
import org.kust.bbs.common.web.State;
import org.kust.bbs.pojo.dto.RoleAddDTO;
import org.kust.bbs.pojo.dto.RoleUpdateDTO;
import org.kust.bbs.pojo.entity.Role;
import org.kust.bbs.pojo.vo.RoleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 */
@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Override
    public JsonPage<RoleVO> listRoles(Integer pageNum, Integer sizeNum) {
        PageHelper.startPage(pageNum, sizeNum);
        List<RoleVO> roles = roleMapper.selectRoles();
        PageInfo pageInfo = new PageInfo<>(roles);
        return JsonPage.restPage(pageInfo);
    }

    @Override
    public RoleVO queryRole(String name) {
        return roleMapper.selectRoleByName(name);
    }

    @Override
    public void addRole(RoleAddDTO roleAddDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleAddDTO, role);
        roleMapper.insertRole(role);
    }

    @Override
    public void updateRole(RoleUpdateDTO roleUpdateDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleUpdateDTO, role);
        roleMapper.updateRole(role);
    }

    @Override
    public void deleteRole(Long id) {
        int exist = roleMapper.selectExistRoleById(id);
        if (exist == 0) {
            throw new ServiceException(State.ERR_NOT_FOUND, "当前删除的角色不存在:" + id);
        }
        int count = adminRoleMapper.selectRelationByRoleid(id);
        if (count != 0) {
            throw new ServiceException(State.ERR_UPDATE, "当前角色关联了账号无法删除");
        }
        roleMapper.deleteRol(id);
    }
}
